package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"yuni/model/cache"
	"yuni/pkg"

	"yuni/yunirpc/internal/svc"
	"yuni/yunirpc/yunirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SengSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSengSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SengSmsLogic {
	return &SengSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SengSmsLogic) SengSms(in *yunirpc.SengSmsRequest) (*yunirpc.SengSmsResponse, error) {
	// todo: add your logic here and delete this line
	i, _ := cache.Rdb.Get(l.ctx, "sengCode"+in.Account).Int64()
	if i >= 1 {
		return nil, fmt.Errorf("1分钟内仅允许发送1条验证码")
	}

	code := rand.Intn(9000) + 1000

	sms, err := pkg.SengSms(in.Account, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, fmt.Errorf(sms.Msg)
	}
	cache.Rdb.Set(l.ctx, "smsCode"+in.Account, code, time.Minute*5)
	cache.Rdb.Info(l.ctx, "sengCode"+in.Account)
	cache.Rdb.Expire(l.ctx, "sengCode"+in.Account, time.Minute*1)
	return &yunirpc.SengSmsResponse{}, nil
}
